package com.hunnyhu.tools;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import com.hunnyhu.tools.refresh.XListView;
import com.hunnyhu.tools.refresh.XListView.IXListViewListener;

public class XListViewActivity extends Activity implements IXListViewListener {
	private XListView mListView;
	private XAdapter mAdapter;
	private List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
	private Handler mHandler;
	private SignDao signDao;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		mListView = (XListView) findViewById(R.id.xListView);
		mListView.setPullLoadEnable(true);
		mListView.setXListViewListener(this);
		mHandler = new Handler();
	}
	
	protected void onResume() {
		super.onResume();
		items.clear();
		geneItems();
		mAdapter = new XAdapter(this, items, R.layout.list_item);
		mListView.setAdapter(mAdapter);
	}
	
//	protected void onRestart() {
//		super.onRestart();
//		items.clear();
//		onLoad();
//	}

	private void geneItems() {
		int count = items.size();
		String id = null;
		if (count > 0) {
			Map<String, Object> map = mAdapter.getItem(count - 1);
			id = (String)map.get(DBHelper.C_ID);
		}
		List<Map<String, Object>> list = getSignDao().findListByDate(id);
		if (null != list && !list.isEmpty()) {
			items.addAll(list);
		}
	}

	private void onLoad() {
		mListView.stopRefresh();
		mListView.stopLoadMore();
		mListView.setRefreshTime("刚刚");
	}
	
	protected SignDao getSignDao() {
		if (null == signDao) {
			signDao = new SignDao(this);
		}
		return signDao;
	}
	
	@Override
	public void onRefresh() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				items.clear();
				geneItems();
				// mAdapter.notifyDataSetChanged();
				mAdapter = new XAdapter(XListViewActivity.this, items, R.layout.list_item);
				mListView.setAdapter(mAdapter);
				onLoad();
			}
		});
	}

	@Override
	public void onLoadMore() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				geneItems();
				mAdapter.notifyDataSetChanged();
				onLoad();
			}
		});
	}

}
